<?php 
	set_time_limit(0);
	include("config.php");
    include(INCLUDEDIR."core.php");
	include(INCLUDEDIR."class.smtp.php");
	include(INCLUDEDIR."class.phpmailer.php");
	include("acceso.php");
	
	$tpl = new Plantilla();
	$tpl->setPlantilla("tpl.boletines.html");
	$tpl->prepare();
	
	$institutos = db::getArrayKey("SELECT id_instituto,acronimo FROM institutos ORDER BY acronimo ASC");
	
	
	
	if($_POST['accion']=="enviar_boletin") {
		$titulo = (isset($_POST['titulo']) && !empty($_POST['titulo']))?" - ".stripslashes($_POST['titulo']):"";
		$texto = isset($_POST['texto'])?stripslashes($_POST['texto']):"";
		$id_instituto = isset($_POST['id_instituto'])?intval($_POST['id_instituto']):0;
		if(strlen($texto)<5) redir($_SERVER['PHP_SELF'],"El texto no puede ser vacio.",true);
		$dondeapr = isset($_POST['dondeapr'])?intval($_POST['dondeapr']):0;
		$mail = new PHPMailer();
		$mail->IsHTML(true);
		$mail->Body = $texto;
		$mail->Subject = "DondeAprendo.com ".$titulo;
		$filtros = array();
		$filtros[] = "es_dondeaprendo = '$dondeapr'";
		$filtros[] = "LENGTH(email)>1";
		if($id_instituto>0) $filtros[] = "id_instituto = '$id_instituto'";
		$filtro = "WHERE ".implode(" AND ",$filtros);		
		$query = "SELECT nombre_persona, email FROM personas $filtro";
		echo($query);
		$result = mysql_query($query);		
		?><html><body><pre><?php		
		if($result && mysql_num_rows($result)>0) {
			while($fila = mysql_fetch_assoc($result)) {
				$nombre= $fila['nombre_persona'];
				$email = $fila['email'];
				if(esEmail($email)) {
					$mail->AddAddress($email,$nombre);	
					echo("Enviando correo para $nombre ($email)...\n");
					flush();
					$mail->Send();
					$mail->ClearAddresses();
				}				
			}
		}
		?></pre><script type="text/javascript">window.location = "main.php?m=RWwgbWVuc2FqZSBmdWUgZW52aWFkbyBhIHRvZG9zIGxvcyBkZXN0aW5hdGFyaW9z";</script></body></html><?php
		exit();
	}

	$tpl->newBlock("FORMULARIOAGREGAR");
	$tpl->assign("texto",$texto);
	$tpl->assign("comboinstitutos",genCombo("id_instituto",$institutos,$id_instituto,"-- Todas las Instituciones --"));	
	
	$tpl->Mostrar();
?>